import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:csv/csv.dart';
import 'package:excel/excel.dart';
import 'package:file_selector/file_selector.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_plus/share_plus.dart';
import '../models/note.dart';
import '../models/essay_material.dart';
import '../utils/encoding_util.dart';

class NoteImportResult {
  final List<Note> notes;
  final List<String> errors;
  final bool hasErrors;

  NoteImportResult(this.notes, this.errors) : hasErrors = errors.isNotEmpty;
}

class EssayMaterialImportResult {
  final List<EssayMaterial> materials;
  final List<String> errors;
  final bool hasErrors;

  EssayMaterialImportResult(this.materials, this.errors) : hasErrors = errors.isNotEmpty;
}

class NoteEssayImportExportUtil {
  // 导出笔记到CSV文件
  static Future<String?> exportNotesToCSV(List<Note> notes) async {
    try {
      // 创建CSV数据
      List<List<dynamic>> csvData = [];
      
      // 添加标题行
      csvData.add(['标题', '内容', '分类', '标签', '图片URL', '创建时间', '更新时间']);
      
      // 添加笔记数据
      for (var note in notes) {
        csvData.add([
          note.title,
          note.content,
          note.category,
          note.tags,
          note.imageUrl ?? '',
          note.created_at,
          note.updated_at,
        ]);
      }
      
      // 转换为CSV字符串
      String csvString = const ListToCsvConverter().convert(csvData);
      
      // 添加BOM以支持中文
      List<int> bytes = [0xEF, 0xBB, 0xBF];
      bytes.addAll(utf8.encode(csvString));
      
      // 确定导出路径
      String dirPath;
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\笔记';
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/学习宝库/笔记');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      // 使用指定的目录路径
      final path = '$dirPath/笔记导出_${DateTime.now().millisecondsSinceEpoch}.csv';
      final file = File(path);
      
      // 确保桌面平台目录存在
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      }

      // 写入文件
      await file.writeAsBytes(bytes);

      print('笔记已导出到CSV文件: $path');
      return path;
    } catch (e) {
      print('导出笔记失败: $e');
      return null;
    }
  }

  // 导出作文素材到CSV文件
  static Future<String?> exportEssayMaterialsToCSV(List<EssayMaterial> materials) async {
    try {
      // 创建CSV数据
      List<List<dynamic>> csvData = [];
      
      // 添加标题行
      csvData.add(['标题', '内容', '分类', '标签', '来源', '图片URL', '创建时间', '更新时间']);
      
      // 添加作文素材数据
      for (var material in materials) {
        csvData.add([
          material.title,
          material.content,
          material.category,
          material.tags,
          material.source,
          material.imageUrl ?? '',
          material.createdAt,
          material.updatedAt,
        ]);
      }
      
      // 转换为CSV字符串
      String csvString = const ListToCsvConverter().convert(csvData);
      
      // 添加BOM以支持中文
      List<int> bytes = [0xEF, 0xBB, 0xBF];
      bytes.addAll(utf8.encode(csvString));
      
      // 确定导出路径
      String dirPath;
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\作文素材';
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/学习宝库/作文素材');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      // 使用指定的目录路径
      final path = '$dirPath/作文素材导出_${DateTime.now().millisecondsSinceEpoch}.csv';
      final file = File(path);
      
      // 确保桌面平台目录存在
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      }

      // 写入文件
      await file.writeAsBytes(bytes);

      print('作文素材已导出到CSV文件: $path');
      return path;
    } catch (e) {
      print('导出作文素材失败: $e');
      return null;
    }
  }

  // 导出笔记到Word文档
  static Future<String?> exportNotesToWord(List<Note> notes) async {
    try {
      // 创建Word文档内容
      String wordContent = _generateNoteWordContent(notes);
      
      // 确定导出路径
      String dirPath;
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\笔记';
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/学习宝库/笔记');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      // 使用指定的目录路径
      final path = '$dirPath/笔记导出_${DateTime.now().millisecondsSinceEpoch}.docx';
      final file = File(path);
      
      // 确保桌面平台目录存在
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      }

      // 写入文件
      await file.writeAsString(wordContent, encoding: utf8);

      print('笔记已导出到Word文档: $path');
      return path;
    } catch (e) {
      print('导出笔记到Word失败: $e');
      return null;
    }
  }

  // 导出作文素材到Word文档
  static Future<String?> exportEssayMaterialsToWord(List<EssayMaterial> materials) async {
    try {
      // 创建Word文档内容
      String wordContent = _generateEssayMaterialWordContent(materials);
      
      // 确定导出路径
      String dirPath;
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        // 桌面平台使用固定路径
        dirPath = 'D:\\000\\my-web\\学习宝库\\作文素材';
      } else {
        // 移动平台使用Download/考试宝目录
        try {
          // 请求存储权限
          var status = await Permission.storage.request();
          if (!status.isGranted) {
            throw Exception('需要存储权限才能导出文件');
          }
          
          // 获取外部存储目录
          final directory = await getExternalStorageDirectory();
          if (directory == null) {
            throw Exception('无法获取外部存储目录');
          }
          
          // 获取Download目录 - 内部存储
          final downloadDir = Directory('${directory.path.split('Android')[0]}Download/学习宝库/作文素材');
          dirPath = downloadDir.path;
          
          // 确保目录存在
          if (!await downloadDir.exists()) {
            await downloadDir.create(recursive: true);
          }
        } catch (e) {
          print('设置移动平台导出路径失败: $e');
          throw Exception('设置导出路径失败: $e');
        }
      }
      
      // 使用指定的目录路径
      final path = '$dirPath/作文素材导出_${DateTime.now().millisecondsSinceEpoch}.docx';
      final file = File(path);
      
      // 确保桌面平台目录存在
      if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
        final directory = Directory(dirPath);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
      }

      // 写入文件
      await file.writeAsString(wordContent, encoding: utf8);

      print('作文素材已导出到Word文档: $path');
      return path;
    } catch (e) {
      print('导出作文素材到Word失败: $e');
      return null;
    }
  }

  // 生成笔记Word文档内容
  static String _generateNoteWordContent(List<Note> notes) {
    StringBuffer content = StringBuffer();
    
    // 按分类分组笔记
    Map<String, List<Note>> notesByCategory = {};
    for (var note in notes) {
      String category = note.category.isEmpty ? '未分类' : note.category;
      if (!notesByCategory.containsKey(category)) {
        notesByCategory[category] = [];
      }
      notesByCategory[category]!.add(note);
    }
    
    // 对分类进行排序，未分类放在最后
    List<String> sortedCategories = notesByCategory.keys.toList();
    sortedCategories.sort((a, b) {
      if (a == '未分类') return 1;
      if (b == '未分类') return -1;
      return a.compareTo(b);
    });
    
    // 添加Word文档头部
    content.writeln('<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">');
    content.writeln('<head>');
    content.writeln('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">');
    content.writeln('<meta name="ProgId" content="Word.Document">');
    content.writeln('<meta name="Generator" content="Microsoft Word 15">');
    content.writeln('<meta name="Originator" content="Microsoft Word 15">');
    content.writeln('<title>笔记导出</title>');
    content.writeln('<!--[if gte mso 9]>');
    content.writeln('<xml>');
    content.writeln('<w:WordDocument>');
    content.writeln('<w:View>Print</w:View>');
    content.writeln('<w:Zoom>100</w:Zoom>');
    content.writeln('<w:DoNotOptimizeForBrowser/>');
    content.writeln('</w:WordDocument>');
    content.writeln('</xml>');
    content.writeln('<![endif]-->');
    content.writeln('<style>');
    content.writeln('<!-- /* 样式定义 */');
    content.writeln('body { font-family: "宋体", SimSun, serif; font-size: 12pt; line-height: 1.5; }');
    content.writeln('h1 { font-size: 18pt; font-weight: bold; text-align: center; margin: 20pt 0; }');
    content.writeln('h2 { font-size: 14pt; font-weight: bold; margin: 15pt 0 10pt 0; }');
    content.writeln('p { margin: 8pt 0; }');
    content.writeln('.category-header { font-size: 16pt; font-weight: bold; color: #0066cc; text-align: center; margin: 30pt 0 20pt 0; padding: 15pt; background-color: #f0f8ff; border: 2px solid #0066cc; border-radius: 5pt; }');
    content.writeln('.category-separator { margin: 40pt 0; border-top: 3px double #0066cc; page-break-before: auto; }');
    content.writeln('.note { margin-bottom: 20pt; border-bottom: 1px solid #ccc; padding-bottom: 15pt; }');
    content.writeln('.note-title { font-size: 14pt; font-weight: bold; color: #333; }');
    content.writeln('.note-meta { font-size: 10pt; color: #666; margin: 5pt 0; }');
    content.writeln('.note-content { margin: 10pt 0; text-align: justify; }');
    content.writeln('.note-category { font-weight: bold; color: #0066cc; }');
    content.writeln('.note-tags { color: #009900; }');
    content.writeln('.category-summary { font-size: 11pt; color: #666; text-align: center; margin-bottom: 15pt; }');
    content.writeln('img { max-width: 90%; display: block; margin: 10pt 0; }');
    content.writeln('-->');
    content.writeln('</style>');
    content.writeln('</head>');
    content.writeln('<body>');
    
    // 添加标题
    content.writeln('<h1>我的笔记</h1>');
    content.writeln('<p style="text-align: center; color: #666;">导出时间: ${DateTime.now().toString().substring(0, 19)}</p>');
    content.writeln('<p style="text-align: center; color: #666;">共 ${notes.length} 条笔记，${notesByCategory.length} 个分类</p>');
    content.writeln('<hr>');
    
    // 添加目录
    content.writeln('<div style="margin: 20pt 0; padding: 15pt; background-color: #f9f9f9; border: 1px solid #ddd;">');
    content.writeln('<h2 style="margin-top: 0;">📋 分类目录</h2>');
    for (String category in sortedCategories) {
      int noteCount = notesByCategory[category]!.length;
      content.writeln('<p style="margin: 5pt 0;">📁 <strong>${_escapeHtml(category)}</strong> - 共 ${noteCount} 条笔记</p>');
    }
    content.writeln('</div>');
    
    // 按分类添加笔记内容
    int totalNoteIndex = 1;
    for (int categoryIndex = 0; categoryIndex < sortedCategories.length; categoryIndex++) {
      String category = sortedCategories[categoryIndex];
      List<Note> categoryNotes = notesByCategory[category]!;
      
      // 添加分类分隔符（除了第一个分类）
      if (categoryIndex > 0) {
        content.writeln('<div class="category-separator"></div>');
      }
      
      // 添加分类标题
      content.writeln('<div class="category-header">');
      content.writeln('<h2 style="margin: 0; color: #0066cc;">📁 ${_escapeHtml(category)}</h2>');
      content.writeln('<div class="category-summary">本分类包含 ${categoryNotes.length} 条笔记</div>');
      content.writeln('</div>');
      
      // 添加该分类下的所有笔记
      for (int i = 0; i < categoryNotes.length; i++) {
        var note = categoryNotes[i];
        content.writeln('<div class="note">');
        content.writeln('<h2 class="note-title">${totalNoteIndex}. ${_escapeHtml(note.title)}</h2>');
        
        // 添加元信息
        content.writeln('<div class="note-meta">');
        if (note.tags.isNotEmpty) {
          content.writeln('<span class="note-tags">标签: ${_escapeHtml(note.tags)}</span> | ');
        }
        content.writeln('创建时间: ${DateTime.fromMillisecondsSinceEpoch(note.created_at).toString().substring(0, 19)} | 更新时间: ${DateTime.fromMillisecondsSinceEpoch(note.updated_at).toString().substring(0, 19)}');
        content.writeln('</div>');
        
        // 添加笔记内容
        content.writeln('<div class="note-content">');
        // 去除Markdown格式后再进行HTML转义和换行处理
        String cleanContent = _removeMarkdownFormat(note.content);
        content.writeln('<p>${_escapeHtml(cleanContent).replaceAll('\n', '<br>')}</p>');
        content.writeln('</div>');
        
        // 添加图片（如果有）
        if (note.imageUrl != null && note.imageUrl!.isNotEmpty) {
          content.writeln('<div>');
          content.writeln('<p><strong>相关图片:</strong></p>');
          content.writeln('<img src="${note.imageUrl}" alt="笔记图片">');
          content.writeln('</div>');
        }
        
        content.writeln('</div>');
        totalNoteIndex++;
      }
    }
    
    content.writeln('</body>');
    content.writeln('</html>');
    
    return content.toString();
  }

  // 生成作文素材Word文档内容
  static String _generateEssayMaterialWordContent(List<EssayMaterial> materials) {
    StringBuffer content = StringBuffer();
    
    // 添加Word文档头部
    content.writeln('<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">');
    content.writeln('<head>');
    content.writeln('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">');
    content.writeln('<meta name="ProgId" content="Word.Document">');
    content.writeln('<meta name="Generator" content="Microsoft Word 15">');
    content.writeln('<meta name="Originator" content="Microsoft Word 15">');
    content.writeln('<title>作文素材导出</title>');
    content.writeln('<!--[if gte mso 9]>');
    content.writeln('<xml>');
    content.writeln('<w:WordDocument>');
    content.writeln('<w:View>Print</w:View>');
    content.writeln('<w:Zoom>100</w:Zoom>');
    content.writeln('<w:DoNotOptimizeForBrowser/>');
    content.writeln('</w:WordDocument>');
    content.writeln('</xml>');
    content.writeln('<![endif]-->');
    content.writeln('<style>');
    content.writeln('<!-- /* 样式定义 */');
    content.writeln('body { font-family: "宋体", SimSun, serif; font-size: 12pt; line-height: 1.5; }');
    content.writeln('h1 { font-size: 18pt; font-weight: bold; text-align: center; margin: 20pt 0; }');
    content.writeln('h2 { font-size: 14pt; font-weight: bold; margin: 15pt 0 10pt 0; }');
    content.writeln('p { margin: 8pt 0; }');
    content.writeln('.material { margin-bottom: 20pt; border-bottom: 1px solid #ccc; padding-bottom: 15pt; }');
    content.writeln('.material-title { font-size: 14pt; font-weight: bold; color: #333; }');
    content.writeln('.material-meta { font-size: 10pt; color: #666; margin: 5pt 0; }');
    content.writeln('.material-content { margin: 10pt 0; text-align: justify; }');
    content.writeln('.material-category { font-weight: bold; color: #0066cc; }');
    content.writeln('.material-tags { color: #009900; }');
    content.writeln('.material-source { color: #cc6600; }');
    content.writeln('img { max-width: 90%; display: block; margin: 10pt 0; }');
    content.writeln('-->');
    content.writeln('</style>');
    content.writeln('</head>');
    content.writeln('<body>');
    
    // 添加标题
    content.writeln('<h1>作文素材库</h1>');
    content.writeln('<p style="text-align: center; color: #666;">导出时间: ${DateTime.now().toString().substring(0, 19)}</p>');
    content.writeln('<p style="text-align: center; color: #666;">共 ${materials.length} 条素材</p>');
    content.writeln('<hr>');
    
    // 添加作文素材内容
    for (int i = 0; i < materials.length; i++) {
      var material = materials[i];
      content.writeln('<div class="material">');
      content.writeln('<h2 class="material-title">${i + 1}. ${_escapeHtml(material.title)}</h2>');
      
      // 添加元信息
      content.writeln('<div class="material-meta">');
      if (material.category.isNotEmpty) {
        content.writeln('<span class="material-category">分类: ${_escapeHtml(material.category)}</span> | ');
      }
      if (material.tags.isNotEmpty) {
        content.writeln('<span class="material-tags">标签: ${_escapeHtml(material.tags)}</span> | ');
      }
      if (material.source.isNotEmpty) {
        content.writeln('<span class="material-source">来源: ${_escapeHtml(material.source)}</span> | ');
      }
      content.writeln('创建时间: ${material.createdAt} | 更新时间: ${material.updatedAt}');
      content.writeln('</div>');
      
      // 添加素材内容
      content.writeln('<div class="material-content">');
      // 去除Markdown格式后再进行HTML转义和换行处理
      String cleanContent = _removeMarkdownFormat(material.content);
      content.writeln('<p>${_escapeHtml(cleanContent).replaceAll('\n', '<br>')}</p>');
      content.writeln('</div>');
      
      // 添加图片（如果有）
      if (material.imageUrl != null && material.imageUrl!.isNotEmpty) {
        content.writeln('<div>');
        content.writeln('<p><strong>相关图片:</strong></p>');
        content.writeln('<img src="${material.imageUrl}" alt="素材图片">');
        content.writeln('</div>');
      }
      
      content.writeln('</div>');
    }
    
    content.writeln('</body>');
    content.writeln('</html>');
    
    return content.toString();
  }

  // 去除Markdown格式的函数
  static String _removeMarkdownFormat(String text) {
    String result = text;
    
    // 去除标题格式 (# ## ### 等)
    result = result.replaceAll(RegExp(r'^#{1,6}\s+'), '');
    result = result.replaceAll(RegExp(r'^#{1,6}\s+', multiLine: true), '');
    
    // 去除粗体格式 (**text** 或 __text__)
    result = result.replaceAll(RegExp(r'\*\*(.*?)\*\*'), r'$1');
    result = result.replaceAll(RegExp(r'__(.*?)__'), r'$1');
    
    // 去除斜体格式 (*text* 或 _text_)
    result = result.replaceAll(RegExp(r'(?<!\*)\*([^*]+)\*(?!\*)'), r'$1');
    result = result.replaceAll(RegExp(r'(?<!_)_([^_]+)_(?!_)'), r'$1');
    
    // 去除删除线格式 (~~text~~)
    result = result.replaceAll(RegExp(r'~~(.*?)~~'), r'$1');
    
    // 去除行内代码格式 (`code`)
    result = result.replaceAll(RegExp(r'`([^`]+)`'), r'$1');
    
    // 去除代码块格式 (```code```)
    result = result.replaceAll(RegExp(r'```[\s\S]*?```'), '');
    result = result.replaceAll(RegExp(r'```.*'), '');
    
    // 去除链接格式 [text](url)
    result = result.replaceAll(RegExp(r'\[([^\]]+)\]\([^)]+\)'), r'$1');
    
    // 去除图片格式 ![alt](url)
    result = result.replaceAll(RegExp(r'!\[([^\]]*)\]\([^)]+\)'), r'$1');
    
    // 去除引用格式 (> text)
    result = result.replaceAll(RegExp(r'^>\s*', multiLine: true), '');
    
    // 去除无序列表格式 (- * +)
    result = result.replaceAll(RegExp(r'^[\s]*[-*+]\s+', multiLine: true), '');
    
    // 去除有序列表格式 (1. 2. 等)
    result = result.replaceAll(RegExp(r'^[\s]*\d+\.\s+', multiLine: true), '');
    
    // 去除水平分割线 (--- *** ___)
    result = result.replaceAll(RegExp(r'^[\s]*[-*_]{3,}[\s]*$', multiLine: true), '');
    
    // 去除表格格式的分隔符
    result = result.replaceAll(RegExp(r'\|'), ' ');
    result = result.replaceAll(RegExp(r'^[\s]*:?-+:?[\s]*$', multiLine: true), '');
    
    // 清理多余的空行
    result = result.replaceAll(RegExp(r'\n\s*\n\s*\n'), '\n\n');
    result = result.replaceAll(RegExp(r'^\s+|\s+$'), '');
    
    return result;
  }

  // HTML转义函数
  static String _escapeHtml(String text) {
    return text
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#39;');
  }

  // 导入笔记从CSV或Excel文件
  static Future<NoteImportResult> importNotesFromCSVOrExcel() async {
    List<Note> notes = [];
    List<String> errors = [];

    try {
      // 选择文件
      const XTypeGroup typeGroup = XTypeGroup(
        label: 'CSV和Excel文件',
        extensions: ['csv', 'xlsx', 'xls'],
      );
      final XFile? file = await openFile(acceptedTypeGroups: [typeGroup]);
      
      if (file == null) {
        errors.add('未选择文件');
        return NoteImportResult(notes, errors);
      }

      // 读取文件内容
      final fileData = await _readFile(file);
      if (fileData == null) {
        errors.add('读取文件失败');
        return NoteImportResult(notes, errors);
      }

      // 根据文件扩展名处理
      String fileName = file.name.toLowerCase();
      List<List<dynamic>> rows = [];

      if (fileName.endsWith('.csv')) {
        // 处理CSV文件
        String content = EncodingUtil.decodeBytes(fileData.data);
        rows = const CsvToListConverter().convert(content);
      } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
        // 处理Excel文件
        var excel = Excel.decodeBytes(fileData.data);
        var table = excel.tables[excel.tables.keys.first];
        if (table != null) {
          for (var row in table.rows) {
            rows.add(row.map((cell) => cell?.value?.toString() ?? '').toList());
          }
        }
      }

      if (rows.isEmpty) {
        errors.add('文件内容为空');
        return NoteImportResult(notes, errors);
      }

      // 跳过标题行
      if (rows.length > 1) {
        for (int i = 1; i < rows.length; i++) {
          try {
            var row = rows[i];
            if (row.length >= 7) {
              var note = Note(
                id: DateTime.now().millisecondsSinceEpoch + i,
                title: row[0]?.toString() ?? '',
                content: row[1]?.toString() ?? '',
                category: row[2]?.toString() ?? '',
                tags: row[3]?.toString() ?? '',
                imageUrl: row[4]?.toString().isEmpty == true ? null : row[4]?.toString(),
                created_at: int.tryParse(row[5]?.toString() ?? '') ?? DateTime.now().millisecondsSinceEpoch,
                updated_at: int.tryParse(row[6]?.toString() ?? '') ?? DateTime.now().millisecondsSinceEpoch,
              );
              notes.add(note);
            } else {
              errors.add('第${i + 1}行数据格式不正确');
            }
          } catch (e) {
            errors.add('第${i + 1}行处理失败: $e');
          }
        }
      }

      return NoteImportResult(notes, errors);
    } catch (e) {
      errors.add('导入失败: $e');
      return NoteImportResult(notes, errors);
    }
  }

  // 导入作文素材从CSV或Excel文件
  static Future<EssayMaterialImportResult> importEssayMaterialsFromCSVOrExcel() async {
    List<EssayMaterial> materials = [];
    List<String> errors = [];

    try {
      // 选择文件
      const XTypeGroup typeGroup = XTypeGroup(
        label: 'CSV和Excel文件',
        extensions: ['csv', 'xlsx', 'xls'],
      );
      final XFile? file = await openFile(acceptedTypeGroups: [typeGroup]);
      
      if (file == null) {
        errors.add('未选择文件');
        return EssayMaterialImportResult(materials, errors);
      }

      // 读取文件内容
      final fileData = await _readFile(file);
      if (fileData == null) {
        errors.add('读取文件失败');
        return EssayMaterialImportResult(materials, errors);
      }

      // 根据文件扩展名处理
      String fileName = file.name.toLowerCase();
      List<List<dynamic>> rows = [];

      if (fileName.endsWith('.csv')) {
        // 处理CSV文件
        String content = EncodingUtil.decodeBytes(fileData.data);
        rows = const CsvToListConverter().convert(content);
      } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
        // 处理Excel文件
        var excel = Excel.decodeBytes(fileData.data);
        var table = excel.tables[excel.tables.keys.first];
        if (table != null) {
          for (var row in table.rows) {
            rows.add(row.map((cell) => cell?.value?.toString() ?? '').toList());
          }
        }
      }

      if (rows.isEmpty) {
        errors.add('文件内容为空');
        return EssayMaterialImportResult(materials, errors);
      }

      // 跳过标题行
      if (rows.length > 1) {
        for (int i = 1; i < rows.length; i++) {
          try {
            var row = rows[i];
            if (row.length >= 8) {
              var material = EssayMaterial(
                id: DateTime.now().millisecondsSinceEpoch + i,
                title: row[0]?.toString() ?? '',
                content: row[1]?.toString() ?? '',
                category: row[2]?.toString() ?? '',
                tags: row[3]?.toString() ?? '',
                source: row[4]?.toString() ?? '',
                imageUrl: row[5]?.toString().isEmpty == true ? null : row[5]?.toString(),
                createdAt: int.tryParse(row[6]?.toString() ?? '') ?? DateTime.now().millisecondsSinceEpoch,
                updatedAt: int.tryParse(row[7]?.toString() ?? '') ?? DateTime.now().millisecondsSinceEpoch,
              );
              materials.add(material);
            } else {
              errors.add('第${i + 1}行数据格式不正确');
            }
          } catch (e) {
            errors.add('第${i + 1}行处理失败: $e');
          }
        }
      }

      return EssayMaterialImportResult(materials, errors);
    } catch (e) {
      errors.add('导入失败: $e');
      return EssayMaterialImportResult(materials, errors);
    }
  }

  // 读取文件内容
  static Future<_FileReadResult?> _readFile(XFile file) async {
    try {
      final bytes = await file.readAsBytes();
      return _FileReadResult(bytes);
    } catch (e) {
      print('读取文件失败: $e');
      return null;
    }
  }
}

class _FileReadResult {
  final Uint8List data;
  
  _FileReadResult(this.data);
}